﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management;

namespace USBListener
{
    public partial class Form1 : Form
    {
        delegate void SetTextCallback(string text);
        private ManagementEventWatcher insertWatcher = null;
        private ManagementEventWatcher removeWatcher = null;  


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            USBDevicesListener();
        }

        private void USBDevicesListener()
        {
            ManagementScope Scope = new ManagementScope("root\\CIMV2");
            TimeSpan timeSpan = new TimeSpan(0, 0, 0, 1);
            Scope.Options.EnablePrivileges = true;
            WqlEventQuery InsertQuery = new WqlEventQuery("__InstanceCreationEvent",
                        timeSpan,
                        "TargetInstance isa 'Win32_USBControllerDevice'");

            insertWatcher = new ManagementEventWatcher(Scope, InsertQuery);
            insertWatcher.EventArrived += new EventArrivedEventHandler(HandleUSBEvent);
            insertWatcher.Start();

            WqlEventQuery RemoveQuery = new WqlEventQuery("__InstanceDeletionEvent",
                        timeSpan,
                        "TargetInstance isa 'Win32_USBControllerDevice'");

            removeWatcher = new ManagementEventWatcher(Scope, RemoveQuery);
            removeWatcher.EventArrived += new EventArrivedEventHandler(HandleUSBEvent);
            removeWatcher.Start();

            //SELECT * FROM Win32_DeviceChangeEvent
            //select * from Win32_VolumeChangeEvent
            //string queryStr = "SELECT * FROM Win32_USBController";
            //SelectQuery selectQuery = new SelectQuery(queryStr);
            //WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent");
            //getwatcher = new ManagementEventWatcher(query);
            //getwatcher.EventArrived += new EventArrivedEventHandler(HandleUSBEvent);
            //getwatcher.Start();
        }

        void HandleUSBEvent(object sender, EventArrivedEventArgs e)
        {
            ManagementBaseObject mbo = e.NewEvent["TargetInstance"] as ManagementBaseObject;
            if (mbo != null )//&& mbo.ClassPath.ClassName == "Win32_USBControllerDevice")
            {
                String Antecedent = (mbo["Antecedent"] as String).Replace("\"", String.Empty).Split(new Char[] { '=' })[1];
                String Dependent = (mbo["Dependent"] as String).Replace("\"", String.Empty).Split(new Char[] { '=' })[1];
                SetTextSafeThread(string.Format("Antecedent = {0, -20}, Dependent = {1, -20}", Antecedent, Dependent)+"\n");
            }
        }

        private void SetTextSafeThread(string text)
        {
            if (this.textBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetTextSafeThread);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.textBox1.AppendText(text);
            }
        }

        private void FormDestory(object sender, EventArgs e)
        {
            if (insertWatcher != null)
                insertWatcher.Stop();
            if (removeWatcher != null)
                removeWatcher.Stop();
        }
    }
}
